package com.kr.weitao.util;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by maoweidong on 2016/10/27.
 */
public class UrlUtil {
    private static URL url;
    private static HttpURLConnection con;
    private static int state = -1;

    /**
     * 功能：检测当前URL是否可连接或是否有效,
     * 描述：最多连接网络 5 次, 如果 5 次都不成功，视为该地址不可用
     *
     * @param urlStr 指定URL网络地址
     * @return URL
     */
    public synchronized int isConnect(String urlStr) {
        int flg = -1;
        int counts = 0;
        if (urlStr == null || urlStr.length() <= 0) {
            return flg;
        }
        while (counts < 5) {
            try {
                url = new URL(urlStr);
                con = (HttpURLConnection) url.openConnection();
                state = con.getResponseCode();
                if (state == 200) {
                    flg = 0;
                }
                break;
            } catch (Exception ex) {
                counts++;
                urlStr = null;
                continue;
            }
        }
        return flg;
    }
}